package design_pattern.TwoPhaseTermination;

import java.io.*;
import java.net.Socket;

/**
 * @Author: 蔡翔
 * @Date: 2019/11/19 8:40
 * @Version 1.0
 */
public class ClientHandler implements Runnable{
    private final Socket socket;
    private volatile boolean running = true;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //try(。。。)里面执行完 会自动销毁
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter printWriter = new PrintWriter(outputStream)
        ){
            while (running){
                String message = bufferedReader.readLine();
                if(message == null){
                    break;
                }
                System.out.println("Come from client :"+message);
                printWriter.write("echo :"+message);
                printWriter.flush();
            }
        }catch (Exception e){
            //如果客户端 自己出现异常 那就
            this.running = true;
        }finally {
            this.stop();
        }
    }

    public void stop() {
        if(running){
            return;
        }
        this.running = false;
        try {
            this.socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
